﻿using System;
using System.Web.UI;
using ChannelVN.CMS.Common;
using ChannelVN.CMS.DynamicLayout.Entity;
using ChannelVN.CMS.DynamicLayout.FrontEnd.Common;

namespace ChannelVN.CMS.DynamicLayout.FrontEnd.Base
{
    public abstract class ControlContainerBase : Page
    {
        protected override void OnPreLoad(EventArgs e)
        {
            if (!IsPostBack)
            {
                if (PostDataFromAdmin.SecretKey == ConfigValues.DynamicLayoutSecretKey)
                {
                    if (PostDataFromAdmin.IsLoadControlAction)
                    {
                        var jsonControlDetail = PostDataFromAdmin.ControlDetail;
                        var controlDetail = NewtonJson.Deserialize<FullModuleInPageWithConfigEntity>(jsonControlDetail);

                        if (null != controlDetail && null != controlDetail.Module &&
                            !string.IsNullOrEmpty(controlDetail.Module.ModuleConfigSrc))
                        {
                            var path = controlDetail.SkinSrc;
                            if (!path.StartsWith("/")) path = "/" + path;

                            var control = LoadControl(path) as DynamicControlBase;
                            if (null != control)
                            {
                                control.ControlInfo = controlDetail;
                                control.IsDesignMode = true;
                                Controls.Add(control);
                            }
                        }
                    }
                    else if (PostDataFromAdmin.IsLoadConfigAction)
                    {
                        var jsonControlDetail = PostDataFromAdmin.ControlDetail;
                        var controlDetail = NewtonJson.Deserialize<FullModuleInPageWithConfigEntity>(jsonControlDetail);

                        if (null != controlDetail && null != controlDetail.Module &&
                            !string.IsNullOrEmpty(controlDetail.Module.ModuleConfigSrc))
                        {
                            var path = controlDetail.Module.ModuleConfigSrc;

                            var control = LoadControl(path) as DynamicControlBase;
                            if (null != control)
                            {
                                control.ControlInfo = controlDetail;
                                control.IsDesignMode = false;
                                control.EnableViewState = false;
                                Controls.Add(control);
                            }
                        }
                    }
                }
            }

            base.OnPreLoad(e);
        }
    }
}
